<template>
  <div class="app-container">
    <el-form :inline="true" :model="filters" ref="refForm" class="demo-form-inline filter-container">
      <!--<el-form-item prop="dateType" label="广告时间">-->
        <!--<el-date-picker-->
          <!--v-model="filters.date"-->
          <!--class="filter-item"-->
          <!--type="datetimerange"-->
          <!--range-separator="至"-->
          <!--start-placeholder="开始日期"-->
          <!--end-placeholder="结束日期"-->
          <!--align="right">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <el-form-item label="广告名称：" prop="name">
        <el-input v-model="filters.name"></el-input>
      </el-form-item>
      <el-form-item label="操作人：" prop="operator">
        <el-select v-model="filters.operator">
            <el-option
            :label="'全部'"
            :key="consts.ALL"
            :value="undefined"
          ></el-option>
          <el-option v-for="item in operatorList"
                     :key="item"
                     :label="item"
                     :value="item">
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="显示端：" prop="showClient">
        <el-select v-model="filters.showClient"  @change="changeClient">
           <!-- <el-option
            :label="'全部'"
            :key="consts.ALL"
            :value="undefined"
          ></el-option> -->
          <el-option v-for="(item,index) in consts.DEVICE_TYPE_ACTIVE"
                     :key="index"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="广告位置：" prop="position">
        <!-- <el-cascader
          :options="consts.BANNER_TYPE"
          :show-all-levels="false"
          v-model="wholePosition"
          @change="handleChange"
          >
        </el-cascader> -->
        <el-select v-model="filters.position">
          <!-- <el-option
            :label="'全部'"
            :key="consts.ALL"
            :value="undefined"
          ></el-option> -->
          <el-option v-for="(item,index) in consts.BANNER_TYPE"
                     :key="index"
                     :label="item.title"
                     :value="item.value"
                     v-show="item.type === filters.showClient || item.key === filters.showClient"

                     >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select v-model="filters.status">
          <el-option v-for="item in consts.AD_STATUS"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" v-waves icon="el-icon-search" @click="gridSearch">搜索</el-button>
      <el-button @click="resetFilter">重置</el-button>
    </el-form>

    <el-table :data="tableData.list" v-loading="loading" element-loading-text="给我一点时间" border fit
              highlight-current-row
              style="width: 100%">
      <el-table-column label="开始时间" align="center" width="160px">
        <template slot-scope="{row}">
          {{row.startTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" width="160px">
        <template slot-scope="{row}">
          {{row.endTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="广告名称" align="center" prop="name">
      </el-table-column>
      <el-table-column label="广告类型" align="center" >
        <template slot-scope="{row}">
          <span>{{row.bannerType === 1?'赛事Banner':'普通Banner'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告位置" align="center">
        <template slot-scope="{row}">
          {{row.position | toConverter('BANNER_TYPE')}}
        </template>
      </el-table-column>
      <el-table-column label="显示端" align="center">
        <template slot-scope="{row}">
          {{row.showClientArray | toConverter('DEVICE_TYPE_ACTIVE') | join}}
        </template>
      </el-table-column>
      <el-table-column label="链接地址" align="center" prop="actionUrl">
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <el-tag>
            {{row.status | toConverter('AD_STATUS')}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="creator">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button v-if="roleCheck('edit')" type="text"
                     @click="openDialog({dialogName: 'advertising-edit',
                     props: row
                     })">
            编辑
          </el-button>
          <el-button v-if="roleCheck('del')"  type="text" @click="handleDelete(row)">删除</el-button>
          <el-button type="text" @click="toggleStatus(row)" v-if="row.status === 3 && roleCheck('switch')">启用</el-button>
          <el-button type="text" @click="toggleStatus(row)" v-else-if="roleCheck('switch')">禁用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"
                     :current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"
                     :layout="gridLayout" :total="tableData.total">
      </el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" :before-close="() => {dialogVisible = false}">
      <advertising-edit style="max-height:60vh; overflow: auto"
                        :id="dialogProps.id"
                        :row-data="dialogProps"
                  @on-success="dialogVisible = false;doGet({action: 'getGrid'})"
                  v-if="dialogName === 'advertising-edit'"/>
    </el-dialog>
  </div>
</template>

<script>
import { form, grid, dialog } from '@/build';

import {
  marketingAdvertisementUpdateStatus as statusApi,
  marketingAdvertisementOperatorApi as operatorApi,
  marketingAdvertisementDeleteApi as deleteApi,
  marketingAdvertisementListApi as listApi,
} from '@/services/api/marketing';

import AdvertisingEdit from './advertisingEdit';

export default {
  name: 'offer-list',

  mixins: [form, grid, dialog],

  components: {
    AdvertisingEdit,
  },

  data() {
    return {
      operatorList: [],
      tableData: {
        list: [],
        total: 0,
      },
      wholePosition: undefined,
      filters: {
        operator: undefined,
        type: undefined,
        position: undefined,
        showClient: 0,
        status: consts.ALL,
        page: 1,
        size: 20,
      },
      filterDateType: false,
    };
  },
  watch: {
    $route: {
      handler(newVal) {
        const freshList = localStorage.getItem('freshlist');
        if (freshList) {
          this.doGet({ action: 'getGrid' });
          localStorage.removeItem('freshlist');
        }
      },
    },
  },
  methods: {
    changeClient(val) {
      if (val === 2 && this.filters.position < 7) {
        this.filters.position = undefined;
      } else if (val < 2 && this.filters.position >= 7) {
        this.filters.position = undefined;
      }
    },
    handleChange(value) {
      if (value && value.length == 2) {
        this.filters.position = value[1];
      }
    },
    handleDelete({ id }) {
      this.$confirm('确定要删除此广告吗？（删除后前台则不显示此广告图）', '删除公告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteApi({
          id,
        }).then(([result, data]) => {
          if (result) {
            this.doGet({ action: 'getGrid' });
            this.$message({
              type: 'success',
              message: '删除成功!',
            });
          } else {
            this.$message({
              type: 'error',
              message: `删除失败!${data.message}`,
            });
          }
        });
      })
        .catch(() => {
        });
    },


    toggleStatus({ id, status }) {
      const action = status !== 3 ? '禁用' : '启用';
      this.$confirm(`确定要${action}此广告吗？`, `${action}广告`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        statusApi({
          id,
          status: status !== 3 ? 1 : 0,
        }).then(([result, data]) => {
          if (result) {
            this.doGet({ action: 'getGrid' });
            this.$message({
              type: 'success',
              message: `${action}成功!`,
            });
          } else {
            this.$message({
              type: 'error',
              message: `${action}失败!${data.message}`,
            });
          }
        });
      })
        .catch(() => {
        });
    },

    resetFilter() {
      this.resetForm('refForm');
      this.gridSearch();
    },
  },

  mounted() {
    this.bindGet(operatorApi, 'operatorList', {});

    this.bindGet(listApi, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
    });

    this.getAll();
  },
};
</script>
